import axios from "axios";
import type { AxiosRequestConfig, AxiosResponse, AxiosError } from 'axios';
import { message } from 'ant-design-vue';
import { getToken, getUserId, removeToken , removeUserId} from "@/utils/auth";
import { isBlob } from "@/utils/index";

const baseConfig = {
  timeout: 60000 * 10,
  baseURL: import.meta.env.VITE_BASE_URL,
  // 跨域请求时允许携带cookie，默认false返回的响应也会忽略cookie
  withCredentials: true,
  headers: {
    'Content-Type': 'application/json',
  },
}

export const service = axios.create(baseConfig);

export interface customRequestConfig {
  closeGlobalLoading?: boolean       // 是否关闭全局加载，默认启用 
  GetWholeResponse?: boolean    // 是否返回完整响应数据，默认返回res.data
  loadingTip?: string          // 加载图标下方显示的文字
  [key: string]: any
}
interface RequestConfig extends AxiosRequestConfig, customRequestConfig { }

const serverRequest: (config: any) => any = (config: RequestConfig) => {
  config.headers['globalUserId'] = getUserId();
  config.headers['zuulToken'] = getToken();
  config.data = Object.assign(config.data ? config.data : {}, { globalUserId: getUserId(), zuulToken: getToken() });
  if (import.meta.env.CRYPTO) {
    config.headers['filterId'] = 'xss';
    config.data = config.data && window.PazlAesGcm.encryptString(config.data, getUserId(), getToken());
  }

  return config;
}
const serverRequestErr = (err: AxiosError) => {
  message.error('请求失败');
  return Promise.reject(err);
}
const serverResoponse = (res: AxiosResponse) => {
  const { status, data } = res;
  console.log(res);
  
  if (status == 200) {
    if (isBlob(data)) {
      return data;
    }
    if (data.status.code == 0) {
      return data.data ? data.data : true;
    } else {
      message.error(data.status.msg + (data.data?data.data:''));
      return false;
    }
  } else {
    message.error('响应错误');
    return false;
  }
}
const serverResponseErr = (err: AxiosError<any, any>) => {
  if (err.response) {
    if (err.response.status == 401) {
      removeToken();
      removeUserId();
      setTimeout(() => {
        location.reload();
      }, 500);
    };
    // 如果能接收到服务器的响应
    message.error('响应失败');
    return false;
  }
  else {
    message.error('network err!');
    return false;
  }
}

service.interceptors.request.use(serverRequest, serverRequestErr);
service.interceptors.response.use(serverResoponse, serverResponseErr);